package pl.polidea.imf.common.java.impl.http;

import java.io.IOException;
import java.io.OutputStream;

public class TimeoutingOutputStream extends OutputStream {

	private OutputStream encapsulated;
	private ConnectionTimeOutWatchDog watchDog;

	public TimeoutingOutputStream(OutputStream out, ConnectionTimeOutWatchDog watchDog) {
		if (out == null || watchDog == null) {
			throw new IllegalArgumentException("null's must not be supplied");
		}
		encapsulated = out;
		this.watchDog = watchDog;
	}

	public void close() throws IOException {
		try {
			watchDog.watch();
			encapsulated.close();
			watchDog.cancel();
		} catch (IOException e) {
			GenericHttpConnectionImpl.setConnectionAvailability(false);
			throw e;
		}
	}

	public void flush() throws IOException {
		try {
			watchDog.watch();
			encapsulated.flush();
			watchDog.cancel();
		} catch (IOException e) {
			GenericHttpConnectionImpl.setConnectionAvailability(false);
			throw e;
		}

	}

	public void write(byte[] b, int off, int len) throws IOException {
		try {
			encapsulated.write(b, off, len);
		} catch (IOException e) {
			GenericHttpConnectionImpl.setConnectionAvailability(false);
			throw e;
		}
	}

	public void write(byte[] b) throws IOException {
		try {
			encapsulated.write(b);
		} catch (IOException e) {
			GenericHttpConnectionImpl.setConnectionAvailability(false);
			throw e;
		}
	}

	public void write(int b) throws IOException {
		try{
			encapsulated.write(b);
		}
		catch(IOException e){
			GenericHttpConnectionImpl.setConnectionAvailability(false);
			throw e;
		}
	}

}
